#include "DataIndex.hpp"
#include <filesystem>
#include <spdlog/spdlog.h>

DataIndex::~DataIndex()
{
  if(oIndex.is_open())
    oIndex.close();
  if(oData.is_open())
    oData.close();
}

void DataIndex::Start(const std::filesystem::path& savepath,const BaseFormatAdditionalInf& additional)
{
  if(std::filesystem::exists(savepath))
    throw std::runtime_error("Current Path exists");
  if(!std::filesystem::create_directory(savepath))
    throw std::runtime_error("Create Save Directory Failed");
  oIndex.open(savepath/"index",std::ios::trunc);
  oData.open(savepath/"data",std::ios::trunc);
  if(!oIndex.is_open() || !oData.is_open())
    throw std::runtime_error("Can't open file to write");
  oIndex
    <<additional.imgWidth<<std::endl
    <<additional.imgHeight<<std::endl
    <<(int)(additional.pixelType==BaseCamera::ImageType::GREY ? 1 : 3)
    <<std::endl;
}

void DataIndex::FileSaveFuncCall(const ImageType& image)
{
  try
  {
    oData.write((char*)image.data,image.size);
    if(!oData.good())
      throw std::runtime_error("Can't write data to FileData");
    oIndex<<image.frameID<<std::endl;
    if(!oIndex.good())
      throw std::runtime_error("Cant't write data to FileIndex");
  }
  catch(const std::runtime_error& e)
  {
    spdlog::error(std::format("DataIndex ERROR : {}",e.what()));
    throw;
  }
}

void DataIndex::Stop()
{
  oIndex.close();
  oData.close();
}


